package com.shangyitong.yygh_hosp.receive;

import com.rabbitmq.client.Channel;
import com.shangyitong.constant.MqConst;
import com.shangyitong.service.RabbitService;
import com.shangyitong.yygh.model.hosp.Schedule;
import com.shangyitong.yygh.vo.msm.MsmVo;
import com.shangyitong.yygh.vo.order.OrderMqVo;
import com.shangyitong.yygh_hosp.repository.HospitalScheduleRepository;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class HospitalReceiver {
    @Autowired
    private HospitalScheduleRepository hospitalScheduleRepository;
    @Autowired
    private RabbitService rabbitService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ORDER, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_ORDER),
            key = {MqConst.ROUTING_ORDER}
    ))
    public void receiver(OrderMqVo orderMqVo, Message message, Channel channel) {
        System.out.println(orderMqVo);
        Schedule schedule = hospitalScheduleRepository.getById(orderMqVo.getScheduleId());
        System.out.println(schedule);
        if (null != schedule.getAvailableNumber()) {
            //下单成功更新预约数
            schedule.setReservedNumber(orderMqVo.getReservedNumber() - 1);
            schedule.setAvailableNumber(orderMqVo.getAvailableNumber() - 1);
            schedule.setUpdateTime(new Date());
            hospitalScheduleRepository.save(schedule);
        } else {
            //取消预约更新预约数
            hospitalScheduleRepository.deleteById(schedule.getId());
        }
        //发送短信
        MsmVo msmVo = orderMqVo.getMsmVo();
        if (null != msmVo) {
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, msmVo);
        }
    }
}
